package net.pm.core.aspect;

import javax.annotation.Resource;

import net.pm.common.toolkit.PMTool;
import net.pm.common.toolkit.date.DateUtils;
import net.pm.core.entities.db.Loginlog;
import net.pm.core.entities.db.Pmuser;
import net.pm.core.service.pmuser.LoginLogServicer;
import net.pm.core.web.BaseController;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

@Aspect
@Component
public class PM_02_LoginLogAspect {

	@Resource(name = "LoginLogServicer")
	private LoginLogServicer logservicer;

	public static final String OWER_KEY = "OWER_KEY"; // 当前登录者对象在modelandview中的key
	public static final String LOGINRESULT_KEY = "LOGINRESULT_KEY"; // 当前登录结果对象在modelandview中的key
	public static final String CLIENTIP_KEY = "CLIENTIP_KEY"; // 当前登录者IP对象在modelandview中的key

	/**
	 * 记录登录日志
	 * 
	 * @param point
	 * @param retval
	 */
	@AfterReturning(value = "execution(public * net.pm.core.web.user.LoginController.loginhandle(..))", returning = "retval")
	public void recordLoginLog(JoinPoint point, Object retval) {

		final BaseController controller = (BaseController) point.getTarget();

		if (controller.aopAbort) {
			return;
		}

		ModelMap model = ((ModelAndView) retval).getModelMap();

		Object loginresultobj = model.get(PM_02_LoginLogAspect.LOGINRESULT_KEY);
		if (PMTool.isNotEmpty(loginresultobj)) {
			Short loginresult = (Short) loginresultobj;
			Object ownerObj = model.get(PM_02_LoginLogAspect.OWER_KEY);
			String clientip = (String) model
					.get(PM_02_LoginLogAspect.CLIENTIP_KEY);

			Loginlog log = new Loginlog();
			log.setLoginIP(clientip);
			log.setLogResult(loginresult);
			log.setPmuser((Pmuser) ownerObj);
			log.setLoginTime(DateUtils.obtainCurrentDate(DateUtils.FORMAT_LONG));

			logservicer.create(log);
		}
		// 登录日志工作完成，删除modelandview无用的对象
		model.remove(PM_02_LoginLogAspect.OWER_KEY);
		model.remove(PM_02_LoginLogAspect.LOGINRESULT_KEY);
		model.remove(PM_02_LoginLogAspect.CLIENTIP_KEY);
	}
}
